const Schema = think.Mongoose.Schema;

module.exports = class extends think.Mongoose {
    get schema() {
        const schema = new Schema({
            username: {
                type: String,
                required: true
            },
            password: {
                type: String,
                required: true
            },
            roles: [{type: Schema.Types.ObjectId, ref: `${this.tablePrefix}Role`}],
            mobile: String,
            email: String,
            status: {
                type: Number,
                default: 1
            },
            remark: {
                type: String,
                default: ''
            },
            deletable: {type: Boolean, default: true},
            editable: {type: Boolean, default: true},
        }, {timestamps: {}, minimize: false});

        const Role = think.mongoose('Role', {}, 'admin');
        const RoleMenu = think.mongoose('RoleMenu', {}, 'admin');
        const Menu = think.mongoose('Menu', {}, 'admin');

        schema.statics.checkMenuAccessPermissionByPath = async function (userId, path) {
            const me = await this.findById(userId).exec();
            const menu = await Menu.findOne({url: path}).exec();
            if (me && menu) {
                const roles = me.roles;
                for (let role of roles) {
                    const roleMenu = await RoleMenu.findOne({roleId: role, menuId: menu._id}).exec();
                    if (!think.isEmpty(roleMenu)) {
                        return true;
                    }
                }
            }

            return false;
        };

        schema.statics.checkMenuAccessPermission = async function (userId, menuId) {
            const me = await this.findById(userId).lean().exec();
            let allowed = false;
            if (me) {
                const roles = me.roles;
                //要查找父角色的权限，这里没有考虑继承关系


                for (let role of roles) {
                    if (await RoleMenu.findOne({roleId: role, menuId: menuId}).exec()) {
                        allowed = true;
                        break
                    }
                }
            }

            return allowed;
        };

        schema.set('toJSON', {virtuals: true});
        schema.set('toObject', {virtuals: true});

        return schema;
    }
};